﻿using Autofac;
using Autofac.Extensions.DependencyInjection;
using OpenMms.Common.Auth;
using OpenMms.Common.Cathe;
using OpenMms.Domain.BLL;
using OpenMms.Domain.Interface;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Text;
using System.Linq;

namespace OpenMms.Factory
{
    /// <summary>
    /// IOC容器
    /// </summary>
    public static class AutofacExt
    {
        #region 注入--郭文昊--2018年12月11日23:24:46
        private static IContainer _container;
        public static IContainer InitAutofac(IServiceCollection services)
        {
            var builder = new ContainerBuilder();

            //注册数据库基础操作
           // services.AddScoped(typeof(IBLLConstruct<>), typeof(BLLConstruct<>));
            //注册缓存操作
            //services.AddScoped(typeof(ICacheContext), typeof(CacheContext));
            //services.AddScoped(typeof(IAuth), typeof(LocalAuth));
           // services.AddScoped(typeof(IHttpContextAccessor), typeof(HttpContextAccessor));
            //注册Service中的对象,Service中的类要以Service结尾，否则注册失败
            builder.RegisterAssemblyTypes(GetAssemblyByName("OpenMms.Domain")).
                Where(a => a.Name.EndsWith("Service")).AsImplementedInterfaces();

            //防止单元测试时已经注入
            if (services.All(u => u.ServiceType != typeof(ICacheContext)))
            {
                services.AddScoped(typeof(ICacheContext), typeof(CacheContext));
            }
            if (services.All(u => u.ServiceType != typeof(IAuth)))
            {
                services.AddScoped(typeof(IAuth), typeof(LocalAuth));
            }
            if (services.All(u => u.ServiceType != typeof(IHttpContextAccessor)))
            {
                services.AddScoped(typeof(IHttpContextAccessor), typeof(HttpContextAccessor));
            }
            if (services.All(u => u.ServiceType != typeof(IBLLConstruct<>)))
            {
                services.AddScoped(typeof(IBLLConstruct<>), typeof(BLLConstruct<>));
            }
            builder.Populate(services);

            _container = builder.Build();
            return _container;

        }
        #endregion

        #region 扫描--郭文昊--2018年12月11日23:24:05
        /// <summary>
        /// 根据程序集名称获取程序集
        /// </summary>
        /// <param name="AssemblyName">程序集名称</param>
        /// <returns></returns>
        public static Assembly GetAssemblyByName(String AssemblyName)
        {
            return Assembly.Load(AssemblyName);
        }
        #endregion
    }
}
